# encoding: utf-8

 
import os
import subprocess
import codecs
import scriptgoodies

def main(env):
	text = env["context"]["selection"]
	os.chdir(env["constants"]["workingDirectory"])
	path = scriptgoodies.getArchivePath(env,env["static"]["cwSaveVoice_archiveName"])
	encoding = env["prefs"]["speechTextOutputEncoding"]
	codecs.open(path + ".txt","w",encoding).write(text if text else env["constants"]["speechTestLine"])
	commandLine = env["prefs"]["speechCommandLine"]
	pathForCommandLine = path.replace("'","\\'")
	command = commandLine % {"input": pathForCommandLine, "output": pathForCommandLine}
	subprocess.call(command,shell=True,stderr=subprocess.PIPE)
	os.remove(path+".txt")
	return [
		("messageBox",env["static"]["cwSaveVoice_successMessage"] % path),
		("moveCursor",0)
	]
